package com.simlink.sns.controller;

import java.util.HashMap;
import java.util.Map;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.simlink.sns.model.User;
import com.simlink.sns.util.ShiroUtils;

@Controller
@RequestMapping("/account")
public class AccountController {

	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String login() {
		User me = ShiroUtils.getUser();
		if (me != null)
			return "redirect:/";

		return "account/login";
	}

	@ResponseBody
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public Map<String, Object> login(@RequestParam("email") String email, @RequestParam("password") String password) {
		UsernamePasswordToken token = new UsernamePasswordToken(email, password);
		Subject subject = SecurityUtils.getSubject();
		try {
			token.setRememberMe(false);// 记住我
			subject.login(token);
		} catch (Exception e) {
			e.printStackTrace();
		}
		Map<String, Object> ret = new HashMap<String, Object>();
		ret.put("status", 200);
		return ret;
	}

	@RequestMapping("/demo")
	public String demo() {
		Object principal = ShiroUtils.getSubjct().getPrincipal();
		User user = ShiroUtils.getUser();
		return "account/login";
	}

	@RequestMapping("/logout")
	public String logout() {
		ShiroUtils.logout();
		return "account/login";
	}
}
